# Copyright (C) 2007 "dbsolution sas" 
#
# This file is part of Weebotee.
#
# Weebotee is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Weebotee is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Weebotee.  If not, see <http://www.gnu.org/licenses/>.

from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.contrib.auth.models import User
from django import newforms as forms
from apps.core.models.Udetail import Udetail
import datetime

from django.contrib.auth.decorators import *
from apps.core.backend.views.forms.paymethod_form import PaymethodForm
from apps.core.models.billing import Billing

@permission_required("is_staff")
def update(request, name, billing_id=None):
    '''
        UPDATE
        
        Effettua inserimento e modifica dei dettagli di pagamento
        @param str name
        @param int billing_id
    '''
    initial = {'user':name}
    if billing_id:
        try: initial.update(Billing.objects.get(pk=billing_id).__dict__)
        except: pass
    if request.POST:
        form = PaymethodForm(request.POST, initial=initial)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("/admin/users/%s/paymethod/" % name)
    else:
        form = PaymethodForm(initial=initial)
    return render_to_response("admin_paymethod_add.html", {'form':form})

@permission_required("is_staff")
def delete(request, name, billing_id):
    try:
        bill = Billing.objects.get(pk=billing_id)
        bill.delete()
    except:
        pass
    return HttpResponseRedirect("/admin/users/%s/paymethod/" % name)

@permission_required("is_staff")
def viewDetails(request, name, billing_id):
    try:
        b = Billing.objects.get(pk=billing_id)
        title = "Dettagli pagamento per %s %s" % (b.user.last_name, b.user.first_name)
        details = b.__dict__
    except Exception, e:
        print "-->",e
    return render_to_response('details_list.html', locals())

@permission_required("is_staff")
def list(request, name):
    user = User.objects.get(username__iexact = name)
    bills = Billing.objects.filter(user__username__exact = name)
    print user, bills
    return render_to_response("admin_paymethod_list.html", locals())
